package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    PurchaseDetailDao purchaseDetailDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    //查询未领取的采购单
    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                //采购单 刚新建，分配
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求/ware/purchase/merge
     * {
     *   purchaseId: 1, //整单id
     *   items:[1,2,3,4] //合并项集合
     * }
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //purchaseId不存在（未选择采购单），则自动创建新采购单进行合并,purchaseId存在，则直接赋值即可，并修改状态 （新建 -> 已分配）
        Long purchaseId = mergeVo.getPurchaseId();
        if (mergeVo.getPurchaseId() == null){
            //创建新采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            //设置状态为:新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 正在采购中的采购需求不能进行合并，确认采购单是0或1才可以合并
        //purchaseId存在(已选择采购单)，则直接赋值即可，并修改状态 （新建 -> 已分配）
        Long finalPurchaseId = purchaseId;//拿到采购单Id
        List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().filter(item -> {
            //筛选出状态为新建的采购需求的item
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailDao.selectById(item);
            return purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATE.getCode();
        }).map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            //更新采购单id
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            //更新状态为已分配
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
    }

    /**
     * 领取采购单
     * [1,2,3,4]//采购单id
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //1.修改采购单
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(purchaseEntity -> {
            //筛选出采购单状态为 新建或者已领取的采购单
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode()
                    || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(purchaseEntity -> {
            //修改采购单状态为 已领取
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());
        //修改采购单
        this.updateBatchById(collect);

        /**
         * 需要转换list集合时使用steam流，只需要去list集合中的元素使用增强for即可
         */
        //2.修改采购需求
        collect.forEach(item -> {
            //根据采购单id查出采购需求
            List<PurchaseDetailEntity> list = purchaseDetailService.queryByPurchaseIds(item.getId());
            //修改采购需求的状态为正在采购
            List<PurchaseDetailEntity> detailEntities = list.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(purchaseDetailEntity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            //修改采购需求
            purchaseDetailService.updateBatchById(detailEntities);
        });
    }

    //完成采购
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) throws Exception {
        /**
         * {
         *    id: 123,//采购单id
         *    items: [ {itemId:1,status:3,reason:""},{itemId:2,status:4,reason:"无货"} ] // reason：完成/失败的需求详情
         *
         * }
         */
        //只要采购需求全部都完成，才可以修改采购单的状态为 已完成,否则是 有异常
        Long id = purchaseDoneVo.getId();
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        //遍历 采购需求
        List<PurchaseDetailEntity> detailEntityList = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //只要采购需求的状态 != 采购失败 就是 已完成
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                purchaseDetailEntity.setStatus(item.getStatus());
                flag = false;
            }else {
                //此条采购需求完成
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //将成功采购的入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                //传入 商品id、仓库id、商品数量
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setPurchaseId(id);
            detailEntityList.add(purchaseDetailEntity);
        }
        //批量更新 采购需求
        purchaseDetailService.updateBatchById(detailEntityList);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);


    }

}